﻿using Lanbt.Core.Entity;
using Lanbt.Core.Entity.Dto;
using Lanbt.Core.Web.Filter;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Diagnostics;

namespace Lanbt.Core.Web.Controllers.Base
{
    [UserAuthorize]
    public class ActionController : ControllerBase
    {
        /// <summary>
        /// 获取当前用户信息
        /// </summary>
        public CurrentUser CurrentUser
        {
            get
            {
                return (CurrentUser)HttpContext.User;
            }
        }

        /// <summary>
        /// 方法AOP异步方法
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            //可以记录操作日志
            Stopwatch sw = new Stopwatch();
            sw.Start();
            var actionExecutedContext = await next();//执行方法体
            sw.Stop();
            if (actionExecutedContext != null && actionExecutedContext.Result != null)
            {
                var result = (Microsoft.AspNetCore.Mvc.ObjectResult)actionExecutedContext.Result;
                if (result != null && result.Value != null)
                {
                    //赋值方法耗时时间
                    ((ResultOutputBase)result.Value).Time = sw.ElapsedMilliseconds;
                    ((ResultOutputBase)result.Value).OperatorId = this.CurrentUser.Id;
                    ((ResultOutputBase)result.Value).OperatorName = this.CurrentUser.Name;
                }
                //查询操作不记录日志
                if(context.HttpContext.Request.Method.ToUpper() != "GET")
                {
                    //记入系统日志
                    //LogHelper<ActionController>.Info(result.Value.ToJson());
                    //使用事件记录日志
                }
            }
            
        }
    }
}
